package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.controller.dto.UserDTO;
import com.example.springboot.entity.User;
import com.example.springboot.service.IUserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody User user) {  //@RequestBody接收前端Json转成后台java对象
        //新增或者更新
        return Result.success(userService.saveOrUpdate(user));
    }

    //登录
    @PostMapping("/login")
    public Result Login(@RequestBody UserDTO userDTO) {  //@RequestBody接收前端Json转成后台java对象
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        //校验是否为空
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        UserDTO dto = userService.login(userDTO);
        return Result.success(dto);
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {  //@RequestBody接收前端Json转成后台java对象
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();

        //校验是否为空
        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_600,"参数错误");
        }
        return Result.success(userService.register(userDTO));
    }

    // 通过用户名查找用户数据
    @GetMapping("/username/{username}")
    public Result findOne(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        //获取当前用户信息
        User currentUser = TokenUtils.getCurrentUser();
        System.out.println("当前用户信息=============" + currentUser.getNickname());
        return Result.success(userService.getOne(queryWrapper));

    }

}
